package org.baicaixiaozhan.learncommon.util;

import com.google.common.base.Strings;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Http 工具集
 *
 * @since 2021/6/30
 * @author baicaixiaozhan
 */
public final class HttpUtils {

    private HttpUtils() {
        throw new AssertionError();
    }

    public static final String UNKNOWN = "unknown";
    public static final String LOCALHOST_MODEL_ONE = "127.0.0.1";
    public static final String LOCALHOST_MODEL_TWE = "0:0:0:0:0:0:0:1";

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }


    /**
     * 获取目标请求 IP 地址
     *
     * @param request 目标请求
     * @return IP 地址
     * @throws UnknownHostException 未知 host 异常
     */
    public static String getIPAddress(HttpServletRequest request) throws UnknownHostException {
        String ip = request.getHeader("x-forwarded-for");
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (LOCALHOST_MODEL_TWE.equals(ip) || LOCALHOST_MODEL_ONE.equals(ip)) {
            ip = InetAddress.getLocalHost().getHostAddress();
        }
        return ip;
    }
}
